package com.example;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: wyp
 * @Date: 2021/9/9 15:55
 * 独占锁&共享锁
 */
public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {

        Cache cache = new Cache();

        for (int i = 0; i < 10; i++) {
            final int key = i;
            new Thread(()->{
                cache.put(String.valueOf(key),new Object());
            },String.valueOf(i)).start();
        }



        for (int i = 0; i < 10; i++) {
            final int key = i;
            new Thread(()->{
                cache.get(String.valueOf(key));
            },String.valueOf(i)).start();
        }
    }
}

class Cache{
    private volatile Map<String,Object> data = new HashMap<>();

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"正在写入:"+key+" 中...");
            Thread.sleep(500);
            data.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入结束。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public Object get(String key){
        Object result = null;
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"正在读取:"+key+" 中...");
            Thread.sleep(500);
            result = data.get(key);
            System.out.println(Thread.currentThread().getName()+"读取结束。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return result;
    }
}
